﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Data;
using MVVMtutorialAdvanced.Web;
using System.Linq;
using Riba.MVVMSL;

namespace MVVMtutorialAdvanced
{
	public class BookAuthors_VM : ViewModelBase
	{
		private BookDTO _book;
		private readonly DomainServices.IDomainServiceBook _domainService;
		public RelayCommand CommandOk { get; private set; }

		//private ObservableCollection<AuthorQDTO> _authorsQ;
		//public ObservableCollection<AuthorQDTO> AuthorsQ
		//{
		//  get { return _authorsQ; }
		//  set { SetPropertyValue(ref _authorsQ, value, () => AuthorsQ); }
		//}

		//private AuthorQDTO _currentEntity;
		//public AuthorQDTO CurrentEntity
		//{
		//  get { return _currentEntity; }
		//  set { SetPropertyValue(ref _currentEntity, value, () => CurrentEntity); }
		//}

		private PagedCollectionView _authorsQ;
		public PagedCollectionView AuthorsQ
		{
			get { return _authorsQ; }
			set { SetPropertyValue(ref _authorsQ, value, () => AuthorsQ); }
		}

		public BookAuthors_VM(DomainServices.IDomainServiceBook domainService)
		{
			_domainService = domainService;
			ExchangeDataAvailable += vm_ExchangeDataAvailable;
			CommandOk = new RelayCommand(OnCommandOk);

			if (IsInDesignToolNonStatic)
				vm_ExchangeDataAvailable(this, null);
		}

		private void vm_ExchangeDataAvailable(object sender, ExchangeDataAvailableEventArgs e)
		{
			if (e != null)
				_book = e.ExchangeData as BookDTO;

			_domainService.GetAuthorsQ
				(
					(data, error) =>
					{
						if (error != null)
						{
							RaiseShowMsgBox(new ShowMsgBoxEventArgs(error.Message, "Authoren lesen"));
							return;
						}

						// Show only authors, who are not already used in Book
						IEnumerable<AuthorQDTO> authors;

						if (IsInDesignToolNonStatic)
						{
							// _book is null in Design Mode -> where !_book.BookAuthorDtos.Any(... does not work
							var l = new List<AuthorQDTO>();
							l.Add(new AuthorQDTO { Id = 1, FirstName = "Author 1", LastName = "l1" });
							authors = l.ToArray();
						}
						else
							authors =
								from author in data
								where !_book.BookAuthorDtos.Any(bookAuthor => bookAuthor.AuthorId == author.Id)
								select author;

						AuthorsQ = new PagedCollectionView(authors);
						AuthorsQ.SortDescriptions.Add(
							new SortDescription("LastName", ListSortDirection.Ascending));

						//AuthorsQ = new ObservableCollection<AuthorQDTO>(authors);
						//if (AuthorsQ.Count > 0)
						//  CurrentEntity = AuthorsQ[0];
					  
						CommandOk.IsEnabled = true;
					}
				);
		}

		private void OnCommandOk(object handler)
		{
			if (Callback != null)
				Callback(this, AuthorsQ.CurrentItem);

			RaiseCloseChildWindowView();
		}
	}
}
